package jkim.plugin.daframe.ext.sql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import jkim.plugin.daframe.ext.sql.model.DaframeSQLLoggerSetupInfo;
import jkim.plugin.daframe.ext.sql.util.DaframeSQLUtils;

import org.eclipse.core.internal.resources.File;
import org.eclipse.core.internal.resources.Folder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class DaframeSQLLogger extends AbstractUIPlugin {

	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(DaframeSQLLogger.class.getName().replaceAll("/", "."));
	// The plug-in ID
	public static final String PLUGIN_ID = getString("daframe.id");
	// line separator
	public static final String NEW_LINE = System.getProperty("line.separator");
	
	public static final String IMAGE_ID_TITLE = getString("daframe.image.title");
	public static final String IMAGE_ID_START = getString("daframe.image.start");
	public static final String IMAGE_ID_STOP = getString("daframe.image.stop");
	public static final String IMAGE_ID_LOAD = getString("daframe.image.load");
	public static final String IMAGE_ID_CLEAR = getString("daframe.image.clear");
	
	private static final Map<String, DaframeSQLLoggerSetupInfo> loggerInfoMap = new HashMap<String, DaframeSQLLoggerSetupInfo>();
	private static DaframeSQLLoggerSetupInfo currentSetupInfo = null;
	// The shared instance
	private static DaframeSQLLogger plugin;
	
	/**
	 * The constructor
	 */
	public DaframeSQLLogger() {
		initializeDaframeLoggerSetupInfo();
		// TODO JKIM open / close project events
//		IWorkspace workspace = ResourcesPlugin.getWorkspace();
//		IResourceChangeListener listener = new IResourceChangeListener() {
//			public void resourceChanged(IResourceChangeEvent event) {
//				if (event.getResource() != null && event.getResource() instanceof IProject) {
//					System.out.println("close!! ");
//				}
//			}
//		};
//		workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE);
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static DaframeSQLLogger getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given
	 * plug-in relative path
	 *
	 * @param path the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}

	@Override
	protected void initializeImageRegistry(ImageRegistry registry) {
		super.initializeImageRegistry(registry);
        ImageDescriptor image = ImageDescriptor.createFromURL(FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(getString("daframe.image.title.path")), null));
        registry.put(IMAGE_ID_TITLE, image);
        image = ImageDescriptor.createFromURL(FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(getString("daframe.image.start.path")), null));
        registry.put(IMAGE_ID_START, image);
        image = ImageDescriptor.createFromURL(FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(getString("daframe.image.stop.path")), null));
        registry.put(IMAGE_ID_STOP, image);
        image = ImageDescriptor.createFromURL(FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(getString("daframe.image.load.path")), null));
        registry.put(IMAGE_ID_LOAD, image);
        image = ImageDescriptor.createFromURL(FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(getString("daframe.image.clear.path")), null));
        registry.put(IMAGE_ID_CLEAR, image);
	}
	
	public static String getString(String key) {
		return RESOURCE_BUNDLE.getString(key);
	}
	
	public static String[] getStrings(String key, String regex) {
		String value = getString(key);
		return value.split(regex);
	}
	
	public static void openError(final String message) {
		Display.getDefault().asyncExec(new Runnable() {
		    public void run() {
		    	ErrorDialog.openError(PlatformUI.getWorkbench()
		    			.getActiveWorkbenchWindow().getShell(), DaframeSQLLogger
		    			.getString("daframe.log.error.dialog.title"), message,
		    			new Status(IStatus.ERROR, DaframeSQLLogger.PLUGIN_ID, message));
		    }
		});
	}
	
	public static void openMessage(final String message) {
		Display.getDefault().asyncExec(new Runnable() {
		    public void run() {
		        MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DaframeSQLLogger
						.getString("daframe.log.info.dialog.title"), message);
		    }
		});
	}
	
	public static List<DaframeSQLLoggerSetupInfo> getSetupInfoList() {
		List<DaframeSQLLoggerSetupInfo> daframeLoggerSetupInfoList = new ArrayList<DaframeSQLLoggerSetupInfo>();
		for (DaframeSQLLoggerSetupInfo setupInfo : loggerInfoMap.values()) {
			daframeLoggerSetupInfoList.add(setupInfo);
		}
		return daframeLoggerSetupInfoList;
	}
	public static void setCurrentSetupInfo(DaframeSQLLoggerSetupInfo setupInfo) {
		currentSetupInfo = setupInfo;
	}
	public static DaframeSQLLoggerSetupInfo getCurrentSetupInfo() {
		return currentSetupInfo;
	}
	public static void initializeDaframeLoggerSetupInfo() {
		loggerInfoMap.clear();
		IWorkspaceRoot r = ResourcesPlugin.getWorkspace().getRoot();
		IProject[] projectArray = r.getProjects();
		Folder projectRoot = null;
		Folder webinfFolder = null;
		Folder confFolder = null;
		String logFolderPath = null;
		String daframeLogFilePath = null;
		File frameworkConfFile = null;
		File logConfFile = null;
		
		Properties frameworkConfProperties = null;
		Properties logConfProperties = null;
		for (IProject project : projectArray) {
			webinfFolder = DaframeSQLUtils.getWEBINFContainer(project);
			if (webinfFolder != null) {
				projectRoot = (Folder) webinfFolder.getParent();
				confFolder = DaframeSQLUtils.getCONFContainer(webinfFolder);
				if (confFolder != null) {
					frameworkConfFile = DaframeSQLUtils.getFrameworkConfFile(confFolder);
					logConfFile = DaframeSQLUtils.getLogConfFile(confFolder);
					if (frameworkConfFile != null && logConfFile != null) {
						frameworkConfProperties = DaframeSQLUtils.getProperty(frameworkConfFile.getRawLocationURI().getRawPath());
						logConfProperties = DaframeSQLUtils.getProperty(logConfFile.getRawLocationURI().getRawPath());
						logFolderPath = DaframeSQLUtils.getLogFolderPath(webinfFolder, frameworkConfProperties);
						if (frameworkConfProperties != null && logFolderPath != null) {
							daframeLogFilePath = DaframeSQLUtils.getDaframeLogFilePath(projectRoot, webinfFolder, frameworkConfProperties, logConfProperties);
							loggerInfoMap.put(project.getName(), new DaframeSQLLoggerSetupInfo(project.getName(), projectRoot, webinfFolder,  daframeLogFilePath, frameworkConfProperties, logConfProperties));
						}
					}
				}
			}
		}
	}
}
